package com.gx303.wximageselect;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.provider.MediaStore;
import android.os.Bundle;

import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gx303.wximageselect.Inter.ImageSelectInterface;
import com.gx303.wximageselect.Inter.ImageSendInterface;
import com.gx303.wximageselect.adapter.ImageRecycleAdapter;
import com.gx303.wximageselect.bean.Folder;
import com.gx303.wximageselect.bean.Image;
import com.gx303.wxselectlibrary.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PopWxImageSelect extends PopupWindow {
    View view1;
    LinearLayout backLayout;//背景
    LinearLayout lay_takephoto;//拍摄
    LinearLayout lay_selectXC;//从相册选择
    LinearLayout lay_cancel;//取消
    TextView tv_takephoto;//文字-拍照
    android.support.v7.widget.RecyclerView recyclerView;
    LinearLayoutManager mLayoutManager;
    Context mContext;
    Activity act;
    
//    ImageSendInterface interface1;
    ImageRecycleAdapter adapter1;
    
    @SuppressLint("NewApi")
	public PopWxImageSelect(Activity act1,int maxselectimagenum,ImageSendInterface isi1)
    {
//    	datas.setSelectImageNull();
    	datas.imageSendInterface1=isi1;
    	datas.MAX_SELECT_IMAGE_NUM=maxselectimagenum;
        act=act1;
        mContext=act1.getApplicationContext();
        view1= LayoutInflater.from(mContext).inflate(R.layout.pop_wx_image_layout,null);
        this.setContentView(view1);
        this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
        this.setHeight(RelativeLayout.LayoutParams.MATCH_PARENT);
        this.setFocusable(true);
        init();
        backLayout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                pop_dismiss();
            }
        });
        lay_cancel.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                pop_dismiss();
            }
        });
        //从相册选择按钮
        lay_selectXC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	//是否有数据
            	if(datas.hasDatasGened)
            	{
	                Intent it_selectFromXc=new Intent();
	                it_selectFromXc.setClass(mContext,PopWxImageSelectFromXc.class);
//	                it_selectFromXc.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
	                it_selectFromXc.putExtra(PopWxImageSelectFromXc.EXTRA_ALL_OR_FOLDER, true);
//	                it_selectFromXc.putExtra(PopWxImageSelectFromXc.EXTRA_SELECT_MODE,0);
	                act.startActivity(it_selectFromXc);
	                dismiss();
            	}
            	else
            	{
            		showNoPhoto();
            	}
            }
        });
        lay_takephoto.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(adapter1.SelectImageNum()==0)
				{
//					Toast.makeText(mContext, "点击了拍照", Toast.LENGTH_SHORT).show();
					datas.imageSendInterface1.takephoto();
				}
				else
				{
					datas.imageSendInterface1.send(adapter1.getSelectImage());
					dismiss();
				}
			}
		});
        mLayoutManager=new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(mLayoutManager);
        act.getLoaderManager().initLoader(0, null, mLoaderCallback);
    }
    private void init()
    {
        backLayout=(LinearLayout)view1.findViewById(R.id.backLayout);
        lay_takephoto=(LinearLayout)view1.findViewById(R.id.lay_takephoto);
        lay_selectXC=(LinearLayout)view1.findViewById(R.id.lay_selectXC);
        lay_cancel=(LinearLayout)view1.findViewById(R.id.lay_cancel);
        tv_takephoto=(TextView)view1.findViewById(R.id.tv_takephoto);
        recyclerView=(android.support.v7.widget.RecyclerView)view1.findViewById(R.id.recyclerView);
    }
    public void pop_dismiss()
    {
        this.dismiss();
    }
    @SuppressLint("NewApi")
	public void startSelect(View parent)
    {
        this.showAtLocation(parent, Gravity.CENTER,0,0);
    }
    
    private void afterGetData()
    {
    	if(datas.hasDatasGened)
    	{
    		//有数据
//    		 for(int i=0;i<datas.images.size();i++)
//             {
//                 Log.e("Unity",datas.images.get(i).path);
//             }
//    		 for(int i=0;i<datas.folders.size();i++)
//             {
//                 Log.e("Unity",datas.folders.get(i).path);
//             }
    		adapter1=new ImageRecycleAdapter(mContext, datas.images,new ImageSelectInterface() {

				@Override
				public void selectImage(Image im1) {
					// TODO Auto-generated method stub
					takePhotoButtonChange();
				}
				
//				@Override
//				public boolean selectImage(Image im1) {
//					// TODO Auto-generated method stub
//					if(!adapter1.SelectImageExists(im1)&&adapter1.SelectImageNum()>=datas.MAX_SELECT_IMAGE_NUM)
//					{
//						//当等于这个个数时，不可以再选
//						Toast.makeText(mContext, mContext.getResources().getString(R.string.wx_image_select_msg_amount_limit), Toast.LENGTH_SHORT).show();
//						return false;
//					}
//					else
//					{
//						//小于的时候可以选
//						adapter1.SelectImage(im1);
//						takePhotoButtonChange();
//						return true;
//					}
//				}

			});
    		WindowManager wm = (WindowManager) mContext
                    .getSystemService(Context.WINDOW_SERVICE);
    		 int height = wm.getDefaultDisplay().getHeight();
    		adapter1.setHeight(height/3);
    		recyclerView.setAdapter(adapter1);
    	}
    	else
    	{
    		
    	}
    }

    @SuppressLint("NewApi")
	private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallback = new LoaderManager.LoaderCallbacks<Cursor>() {

        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.WIDTH,
                MediaStore.Images.Media.HEIGHT};

        @Override
        public android.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
                CursorLoader cursorLoader = new CursorLoader(mContext,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                        null, null, IMAGE_PROJECTION[2] + " DESC");
                return cursorLoader;
        }

        @Override
        public void onLoadFinished(android.content.Loader<Cursor> loader, Cursor data) {
            if (data != null) {
            	ArrayList<Image> images = new ArrayList<Image>();
            	ArrayList<Folder> folders=new ArrayList<Folder>();
                int count = data.getCount();
                if (count > 0) {
                    data.moveToFirst();
                    do {
                        String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                        String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                        long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                        int width=data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
                        int height=data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[5]));
                        Image image = new Image(path, name, dateTime,width,height);
                        images.add(image);
                        if (!datas.hasDatasGened) {
                            // 获取文件夹名称
                            File imageFile = new File(path);
                            File folderFile = imageFile.getParentFile();
                            Folder folder = new Folder();
                            folder.name = folderFile.getName();
                            folder.path = folderFile.getAbsolutePath();
                            folder.cover = image;
                            if (!folders.contains(folder)) {
                            	ArrayList<Image> imageList = new ArrayList<Image>();
                                imageList.add(image);
                                folder.images = imageList;
                                folders.add(folder);
                            } else {
                                // 更新
                                Folder f = folders.get(folders.indexOf(folder));
                                f.images.add(image);
                            }
                        }

                    } while (data.moveToNext());
                    
                    datas.images=images;
                    datas.folders=folders;
                    datas.hasDatasGened=true;
                }
            }
            afterGetData();
        }

        @Override
        public void onLoaderReset(android.content.Loader<Cursor> loader) {

        }
    };

    /**
     * 拍照按钮的改变
     */
    private void takePhotoButtonChange()
    {
    	int num=adapter1.SelectImageNum();
    	if(num==0)
    	{
    		//没有选择图片，拍照按钮叫做拍摄
    		tv_takephoto.setText(mContext.getString(R.string.wx_image_select_takephoto));
    	}
    	else
    	{
    		tv_takephoto.setText(mContext.getString(R.string.wx_image_select_send)+"("+num+mContext.getString(R.string.wx_image_select_sheet)+")");
    	}
    }
    private void showNoPhoto()
    {
    	act.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Toast.makeText(mContext, mContext.getResources().getString(R.string.wx_image_select_nophoto), Toast.LENGTH_SHORT).show();
			}
		});
    	 }
}
